from django.http import HttpResponseRedirect
from django.utils import six
from django.utils.text import get_text_list
# from requests.compat import basestring

import xadmin
from apps.homework.models import HomeWork, UserHomeWork
from apps.operation.models import UserCourse, UserMessage
from apps.users.models import UserProfile
from xadmin.layout import Main, Fieldset, Row, Side


class HomeWorkAdmin(object):
    list_display = ['course', 'name', 'work', 'end_time', 'add_time']
    search_fields = ['course', 'name', 'work', 'end_time', 'add_time']
    list_filter = ['course', 'name', 'work', 'end_time', 'add_time']
    # list_editable = ['degree', 'desc']
    ordering = ['-add_time']
    model_icon = 'fa fa-pencil'

    def save_models(self):
        home_work_obj = self.new_obj
        if not home_work_obj.id:
            home_work_obj.save()
            user_course_list = UserCourse.objects.filter(course=home_work_obj.course).all()

            for user_course in user_course_list:
                usermessage = UserMessage()
                usermessage.user = user_course.user
                usermessage.message = "您的课程:【<a href='/course/lesson/{0}/'>{1}</a>】 发布了新的作业:【<a href='/course/homework/{2}/'>{3}</a>】 截止时间:【{4}】".format(home_work_obj.course.id,home_work_obj.course,
                                                                                   home_work_obj.course.id,home_work_obj.name,
                                                                                   home_work_obj.end_time)
                usermessage.save()

        home_work_obj.save()
    # 拦截请求 保存时操作另一张表  有id就是编辑  没有id就是新建
    # def save_models(self):
    #     obj = self.new_obj
    #     if not obj.id:
    #         obj.save()
    #         course = obj.course
    #         course.students += 1
    #         course.save()


class UserHomeWorkAdmin(object):
    list_display = ['user', 'homework', 'go_to', 'score', 'add_time']
    search_fields = ['user', 'homework', 'add_time', 'score']
    list_filter = ['user', 'homework', 'add_time', 'score']
    # list_editable = ['degree', 'desc']
    ordering = ['-add_time']
    list_editable = ['score']
    model_icon = 'fa fa-sticky-note'

    # def save_models(self):
    #     user_work_obj = self.new_obj
    #     if user_work_obj.id:
    #
    #         print(user_work_obj.score)
    #
    #         user_work_obj.save()
    # def post(self, request, *args, **kwargs):
    #     print(request.POST)


xadmin.site.register(HomeWork, HomeWorkAdmin)
xadmin.site.register(UserHomeWork, UserHomeWorkAdmin)
